<template>
    <div class="search-container">
        <form action="/">
        <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <search-result v-if="isResultShow" :q="searchText" />

    <search-suggestion  :searchText="searchText"
    @search = "onSearch"
    v-else-if="searchText"/>
      <!-- 搜索历史记录 -->
    <search-history  :searchHistories="searchHistories"
    @remove="remove"
    @search = "onSearch"
    v-else/>
    <!-- /搜索历史记录 -->

    </div>
  </template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/localStorage.js'
export default {
  name: 'SearchPage',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || []
    }
  },
  computed: {},
  watch: {
    searchHistories: {
      handler (value) {
        setItem('TOUTIAO_SEARCH_HISTORIES', this.searchHistories)
      },
      immediate: true
    }
  },
  created () {
  },
  methods: {
    remove (index) {
      if (index === -1) {
        this.searchHistories = []
      } else {
        this.searchHistories.splice(index, 1)
      }
    },
    onSearch (val) {
      this.searchText = val
      window.console.log(this.searchText)
      if (!this.searchText) return
      // 添加历史记录
      const index = this.searchHistories.indexOf(this.searchText)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(this.searchText)
      this.isResultShow = true
      window.console.log(this.isResultShow)
    },
    onCancel () {
      this.$router.back()
      window.console.log('cancel')
    }

  }
}
</script>

  <style scoped lang="less">
.search-container {
  .van-search__action {
    color: #fff;
  }
}

</style>
